/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template uploadedFile, choose Tools | Templates
 * and open the template in the editor.
 */
package course.services;

import course.entities.Image;
import course.entities.Record;
import course.entities.User;
import course.entities.UserActivity;
import course.providers.jpa.ImageProvider;
import course.providers.jpa.RecordProvider;
import course.providers.jpa.UserActivityProvider;
import course.webpart.Facade;
import course.ya.doc.from.code.model.ast.StatementTree;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author def
 */
@ManagedBean(name = "createActivityService")
@ViewScoped
public class CreateActivityService extends AUserService implements Serializable {

    @EJB
    private UserActivityProvider activityProvider;

    @EJB
    private RecordProvider recordProvider;

    @EJB
    private ImageProvider imageProvider;

    private String sourceCode;

    public CreateActivityService() {
    }

    public UserActivity createActivity() throws IOException {
        if (sourceCode == null || sourceCode.equals("")) {
            addErrorMessage("Nothing to draw, please write some code!");
            return null;
        }

        UserActivity activity;

        try {
            Facade facade = new Facade(sourceCode);
            List<StatementTree> treeList = facade.run();
            List<byte[]> images = facade.getImages();
            activity = activityProvider.create();

            List<Record> recordList = new ArrayList<>();
            Iterator<StatementTree> sti = treeList.iterator();
            Iterator<byte[]> i = images.iterator();
            while (sti.hasNext() && i.hasNext()) {
                StatementTree tree = sti.next();
                Image img = imageProvider.create();
                img.setName(tree.getName());
                img.setImageFile(i.next());
                imageProvider.update(img);
                Record record = recordProvider.create();
                record.setTree(tree);
                record.setActivity(activity);
                record.setImage(img);
                recordList.add(record);
                recordProvider.update(record);
            }
            
            activity.setUser(getCurrentUser());
            activity.setActivityDate(new Date());
            activity.setClassName(facade.getClassName());
            activity.setRecordList(recordList);
            activity.setSourceCode(sourceCode);
            activityProvider.update(activity);
            User user = getCurrentUser();
            user.getActivities().add(activity);
            userProvider.update(user);
        } catch (Exception ex) {
            addErrorMessage("Sorry, parsing error has occurred! Make sure your code is valid.");
            ex.printStackTrace();
            return null;
        }
        return activity;
    }

    public void loadFile(FileUploadEvent event) {
        try {
            addInfoMessage("\"" + event.getFile().getFileName() + "\" successfully uploaded!");
            InputStream in = event.getFile().getInputstream();
            sourceCode = new Scanner(in, "UTF-8").useDelimiter("\\A").next();
            in.close();

        } catch (IOException ex) {
            Logger.getLogger(CreateActivityService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getSourceCode() {
        return sourceCode;
    }

    public void setSourceCode(String sourceCode) {
        this.sourceCode = sourceCode;
    }

    public UserActivityProvider getActivityProvider() {
        return activityProvider;
    }

    public void setActivityProvider(UserActivityProvider activityProvider) {
        this.activityProvider = activityProvider;
    }

    public RecordProvider getRecordProvider() {
        return recordProvider;
    }

    public void setRecordProvider(RecordProvider recordProvider) {
        this.recordProvider = recordProvider;
    }

    public ImageProvider getImageProvider() {
        return imageProvider;
    }

    public void setImageProvider(ImageProvider imageProvider) {
        this.imageProvider = imageProvider;
    }

}
